﻿using backend;
using backend.Entity;
using backend.Enum;
using backend.Models;
using backend.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace dms.Controllers
{
    [Authorize(Roles = RoleType.Manager)]
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private List<string> roleTypes = new List<string>() { RoleType.Manager, RoleType.User };

        private readonly MyContext _context;
        public UserController(MyContext context)
        {
            _context = context;
        }

        // GET /api/user/list
        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="name">姓名模糊查询</param>
        /// <param name="userName">用户名模糊查询</param>
        /// <param name="role">角色名称</param>
        /// <param name="page">页数</param>
        /// <param name="size">每页数量</param>
        /// <returns></returns>
        [HttpGet]
        [Route("[action]")]
        public MyJsonResult List(string name,string userName, string role,int page=0,int size=20)
        {
            IEnumerable<User> users = _context.Users;
            if (!string.IsNullOrWhiteSpace(name))
            {
                users = users.Where(a => a.Name.Contains(name));
            }
            if (!string.IsNullOrWhiteSpace(userName))
            {
                users = users.Where(a => a.UserName.Contains(userName));
            }
            if (!string.IsNullOrWhiteSpace(role))
            {
                users = users.Where(a => a.Role==role);
            }
            int TotalCount = users.Count();
            return MyJsonResult.Ok(new{ List=users.Skip((page-1)*size).Take(size), TotalCount });
        }

        // POST api/user
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public MyJsonResult Post([FromBody]UserModel model)
        {
            var user = _context.Users.SingleOrDefault(t => t.UserName == model.user_name);
            if (user != null)
            {
                return MyJsonResult.Error("用户已存在");
            }
            if (!roleTypes.Contains(model.role))
            {
                return MyJsonResult.Error("角色设置错误");
            }

            user = new User()
            {
                Name = model.name,
                UserName = model.user_name,
                Role=model.role,
                Pwd = MD5Helper.Get32MD5(model.user_name + "123456"), //默认密码123456
            };
            _context.Users.Add(user);
            _context.SaveChanges();
            return MyJsonResult.Ok(user);
        }

        // PUT api/user?userName=admin
        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPut]
        public MyJsonResult Put([FromQuery, BindRequired] string userName, UserModel model)
        {
            var user = _context.Users.SingleOrDefault(t => t.UserName == userName);
            if (user == null)
            {
                return MyJsonResult.Error("用户信息不存在");
            }
            if (!roleTypes.Contains(model.role))
            {
                return MyJsonResult.Error("角色设置错误");
            }

            user.Name = model.name;
            user.Role = model.role;

            _context.Users.Update(user);
            _context.SaveChanges();
            return MyJsonResult.Ok(user);
        }

        // DELETE api/user?userName=admin
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<MyJsonResult> Delete([BindRequired] string userName)
        {
            var user = _context.Users.SingleOrDefault(t => t.UserName == userName);
            if (user == null)
            {
                return MyJsonResult.Error("用户信息不存在");
            }
            if (_context.Projects.Any(a => a.Users.Contains(user)))
            {
                return MyJsonResult.Error("该用户已分配标注任务，不可删除");
            }
            _context.Users.Remove(user);
            await _context.SaveChangesAsync();
            return MyJsonResult.Ok(user);
        }

        // GET: api/user/users
        /// <summary>
        /// 获取所有普通用户
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("[action]")]
        public MyJsonResult Users()
        {
            IEnumerable<User> users = _context.Users.Where(a=>a.Role==RoleType.User);
            return MyJsonResult.Ok(users);
        }
    }
}
